package com.dingup.api.Util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by wancheng on 2018/8/24.
 */
public class ImageVerifyCodeUtil extends RedisUtils{

    private static Logger logger = LoggerFactory.getLogger(ImageVerifyCodeUtil.class);

    private static class LazyHolder {
        private static final ImageVerifyCodeUtil ourInstance = new ImageVerifyCodeUtil();
    }
    public static ImageVerifyCodeUtil getInstance() {
        return ImageVerifyCodeUtil.LazyHolder.ourInstance;
    }

    private ImageVerifyCodeUtil() {
    }


    private final String RAND_CHECK_CODE_KEY = "RAND_CHECK_CODE_";

    private final Integer EXIST_TIME = 60 * 3;

    private String getKey(String account){
        return RAND_CHECK_CODE_KEY + account;
    }

    public void putCode(String account,String code){
        set(getKey(account),code,EXIST_TIME);
        logger.info("save图形验证码,account={},code={}",account,code);
    }

    public Boolean checkCode(String account,String code) throws Exception {
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(code)){
            throw new Exception("手机号或验证码为空");
        }
        Boolean res = false;
        String codeCache = get(getKey(account));
        if (StringUtils.isEmpty(codeCache)){
            logger.error("验证码已过期或已删除,account={},code={}",account,code);
            throw new Exception("验证码已过期或已删除");
        }
        if (codeCache.toLowerCase().equals(code.toLowerCase())){
            logger.info("图形验证码验证成功,account={},code={}",account,code);
            res = true;
        }else {
            logger.info("图形验证码验证失败,account={},code={}",account,code);
            res = false;
        }
        return res;
    }
    public Boolean deleteCode(String account){
        del(get(account));
        return true;
    }
}
